// export class Queue {
//   constructor() {
//     this.items = [];
//     this.isStart = false;
//   }
//
//   // 1.enqueue():将元素加入到队列中
//   enqueue(element) {
//     element && this.items.push(element);
//   }
//
//   // 2.dequeue():从队列中删除前端元素
//   dequeue() {
//     return this.items.shift();
//   }
//
//   // 3.front():查看前端的元素
//   front() {
//     return this.items[0];
//   }
//
//   // 4.isEmpty:查看队列是否为空
//   isEmpty() {
//     return this.size === 0;
//   }
//
//   get size() {
//     return this.items.length;
//   }
//
//   end() {
//     this.isStart = false;
//   }
//
//   start(callback) {
//     if (this.isEmpty() || this.isStart) return;
//
//     const loop = async callback => {
//       const find = this.dequeue();
//       typeof callback === 'function' && (await callback(find));
//       if (this.size === 0) {
//         this.end();
//       } else {
//         await loop(callback);
//       }
//     };
//
//     loop(callback)
//       .then(r => {})
//       .catch(error => {});
//   }
// }
//
// const modalQueue = new Queue();

export const showModalAsync = ({
  title,
  content,
  showCancel = true,
  cancelText = '取消',
  cancelColor = '#000000',
  confirmText = '确定',
  confirmColor = '#3CC51F',
  success,
  fail,
  complete
}) => {
  const options = {
    success,
    fail,
    complete
  };
  return new Promise((resolve, reject) => {
    uni.showModal({
      title,
      content,
      showCancel,
      cancelText,
      cancelColor,
      confirmText,
      confirmColor,
      success(...args) {
        resolve(...args);
        options.success && options.success(...args);
      },
      fail(...args) {
        resolve(...args);
        options.fail && options.fail(...args);
      },
      complete(...args) {
        options.complete && options.complete(...args);
      }
    });
  });
};

export const showModal = ({
  title,
  content,
  showCancel = true,
  cancelText,
  cancelColor,
  confirmText,
  confirmColor,
  success,
  fail,
  complete
}) => {
  const options = Array.prototype.slice.call(arguments)[0];
  showModalAsync(options)
    .then(r => {})
    .catch(err => {});
};

// 对API完成数据处理
const handleCompleteData = err => {
  const errMsg = err?.errMsg || false;
  if (Boolean(errMsg) && errMsg.indexOf('ok') > -1) {
    err.resultCode = 0;
  } else {
    err.resultCode = -1;
  }
  return err;
};

/**
 *
 * @param timeout
 * @returns {Promise<unknown>}
 */
export const loginAsync = ({ timeout } = {}) => {
  return new Promise(resolve => {
    uni.login({
      timeout,
      success: result => resolve(handleCompleteData(result)),
      fail: error => resolve(handleCompleteData(error))
    });
  });
};

/**
 * 获取用户信息。
 * @param { boolean } withCredentials 是否带上登录态信息。
 * @param { 'zh_CN' | 'zh_TW' | 'en' } lang 指定返回用户信息的语言，默认为 en。更多值请参考下面的说明。
 * @param { string } desc 声明获取用户个人信息后的用途，不超过30个字符 (withCredentials: true，有效)
 *
 * @param provider 登录服务提供商，通过 uni.getProvider 获取
 * @param { number } timeout 超时时间，单位 ms。
 * @param { boolean } isTouch 是否是 touch 事件触发
 * @returns {Promise<unknown>}
 */
export const getUserInfoAsync = ({
  withCredentials = true,
  desc = '微信用户授权登录或注册用户，并完善信息。',
  provider,
  lang = 'zh_CN',
  timeout,
  isTouch = false
} = {}) => {
  return new Promise((resolve, reject) => {
    const options = {
      success: result => resolve(handleCompleteData(result)),
      fail: error => resolve(handleCompleteData(error))
    };
    // #ifndef H5
    if (withCredentials === true && typeof uni.getUserProfile === 'function') {
      if (isTouch === true) return uni.getUserProfile({ ...options, lang, desc });
      return showModalAsync({
        title: '',
        content: desc,
        showCancel: false,
        success() {
          uni.getUserProfile({ ...options, lang, desc: '用于完善用户资料' });
        },
        fail(error) {
          options.fail(handleCompleteData(error));
        }
      });
    }
    uni.getUserInfo({ ...options, withCredentials, lang, provider, timeout });
    // #endif
    // #ifdef H5
    resolve({
      errMsg: 'getUserInfoAsync:fail method: 该平台无该方法。'
    });
    // #endif
  });
};

export const getSystemInfoAsync = () => {
  try {
    return uni.getSystemInfoSync();
  } catch (e) {
    return new Promise(resolve => {
      uni.getSystemInfo({
        success: result => resolve(handleCompleteData(result)),
        fail: error => resolve(handleCompleteData(error))
      });
    });
  }
};

/**
 * 获取网络类型。
 * @returns {Promise<unknown>}
 */
export const getNetworkTypeAsync = () => {
  return new Promise(resolve => {
    uni.getNetworkType({
      success: result => resolve(handleCompleteData(result)),
      fail: error => resolve(handleCompleteData(error))
    });
  });
};

export default new Proxy(
  { getSystemInfoAsync, getNetworkTypeAsync, getUserInfoAsync },
  {
    get(target, key, receiver) {
      return Object.keys(target).includes(key) ? target[key] : uni[key];
    },
    set(target, key, value, receiver) {}
  }
);
